using System;
using System.Collections.Generic;

public class GGActionQueue : BehaviourSingletonInit<GGActionQueue>
{
	private Queue<QueuableAction> actions;

	private QueuableAction currentAction;

	public override void Init()
	{
		actions = new Queue<QueuableAction>();
		currentAction = null;
	}

	public void AddActionToExecution(QueuableAction action)
	{
		actions.Enqueue(action);
		if (currentAction == null)
		{
			RunNextAction();
		}
	}

	private void RunNextAction()
	{
		if (currentAction != null)
		{
			return;
		}
		try
		{
			QueuableAction action = actions.Dequeue();
			RunAction(action);
		}
		catch (InvalidOperationException ex)
		{
			GGDebug.DebugLog("Empty action queue: " + ex.ToString());
		}
	}

	private void RunAction(QueuableAction action)
	{
		currentAction = action;
		currentAction.DoStart(OnActionFinished);
	}

	private void OnActionFinished()
	{
		currentAction.OnDone();
		currentAction = null;
		RunNextAction();
	}

	public void ClearActions()
	{
		if (currentAction != null)
		{
			currentAction.Stop();
			currentAction = null;
		}
		actions.Clear();
	}

	public bool IsEmpty()
	{
		if (currentAction != null)
		{
			return false;
		}
		if (actions.Count > 0)
		{
			return false;
		}
		return true;
	}
}
